/**
 * New node file
 */
var http = require('http');
var util = require('util');
var serverPort = process.argv[2] ? parseInt(process.argv[2]) : 80;
var localjetty = {host:'localhost', port:8080};
var jboss = {host:'192.168.1.105', port:80};
var malldetaildaily = {host:'10.232.127.179', port:8080}
var skipdaily = {host:'10.235.144.67', port:8080}
var mappingConfig = {
	'detail.daily.tmall.net' : localjetty,
	'mdskip.daily.taobao.net' : localjetty
}
http.createServer(function(req, res){
	var headers = req.headers;
	console.log('handle request: ' + headers['host'] + req.url);
    var requestHost = headers['host'].indexOf(':') >0 ? headers['host'].split(":")[0] : headers['host'];
    var requestcache = null;
    var config = mappingConfig[requestHost];
    if(config == null || config == undefined){
    	config = localjetty;
    }
    var destHost = config.host;
    var destPort = config.port;
    var option = {
    	host : destHost,
    	port : destPort,
    	method : req.method,
    	path : req.url,
    	headers : req.headers
    }
    
    option.headers['proxycircle'] = '1'
    
    req.on('data', function(chunk){
    	if(requestcache == null){
    		requestcache = chunk;
    	}else{
    		requestcache = Buffer.concat(requestcache, chunk);
    	}
    });
    
    req.on('error', function(){
    	console.log('error');
    })
    
    req.on('end', function(){
    	setTimeout(function(){
    		var proxyRequest = http.request(option, function(proxyResponse){
	  			res.writeHead(proxyResponse.statusCode, proxyResponse.headers);
	    		proxyResponse.on('data', function(data){
	    			res.write(data);
	    		});
	    		proxyResponse.on('end', function(){
	    			res.end();
	    		})
	    	}).on('error', function(e){
	    		console.log('error proxy '+  e.message + ' url:' + headers['host'] + req.url);
	    		res.end();
	    	});
	    	if(requestcache != null){
	    		proxyRequest.write(requestcache);
	    	}
	    	
	    	proxyRequest.end();
    	
    	}, 1);
    	
    })
}).listen(serverPort, "192.168.1.104");
console.log('server started.Listening port '+ serverPort)